package org.yan.kangaroo.common.util;

import org.apache.commons.io.IOUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;

/**
 * @author wangxian
 * @date 2019/10/15 15:01
 */
public class FileUtils {
    public static void downloadFile(HttpServletResponse response, InputStream inputStream, String fileName) throws IOException {
        ServletOutputStream outputStream = response.getOutputStream();
        response.setContentType("multipart/form-data");
        response.setCharacterEncoding("utf-8");
        String filename = URLEncoder.encode(fileName, "utf-8");
        response.setHeader("Content-disposition", "attachment;filename=" + filename);
        IOUtils.copy(inputStream, outputStream);
        outputStream.flush();
        outputStream.close();
    }

    public static void preview(HttpServletResponse response, InputStream inputStream) throws IOException {
        ServletOutputStream outputStream = response.getOutputStream();
        IOUtils.copy(inputStream, outputStream);
        outputStream.flush();
        outputStream.close();
    }

    public static void preview(HttpServletResponse response, byte[] bytes) throws IOException {
        ServletOutputStream outputStream = response.getOutputStream();
        IOUtils.write(bytes, outputStream);
        outputStream.flush();
        outputStream.close();
    }
}
